# coding: utf-8
"""
HTML5的相关工具方法/类
"""

from app.constants import user_agents, mobile_view_spec
from collections import OrderedDict

from flask.views import MethodView, View
# from apps.sns.models import WechatActiveOauth

import urllib, urllib2
import json


def get_user_agent(request):
    result = int(request.args.get("landing_page", user_agents.DEFAULT))
    user_agent = request.headers.get('USER_AGENT', "").lower()
    if result:
        pass
    elif "iphone" in user_agent:
        result = user_agents.IPHONE
    elif "ipad" in user_agent:
        result = user_agents.IPAD
    elif "ipod" in user_agent:
        result = user_agents.IPOD
    elif "android" in user_agent:
        result = user_agents.ANDROID
    return result


def get_app_version(request):
    # app_version = request.session.get('app_version')
    app_version = request.breadtrip.version
    user_agent = request.headers.get('USER_AGENT', "").lower()
    if app_version:
        if 'vacation' in user_agent:
            app_version = app_version.to_tags()[0]
        else:
            app_version = app_version.to_tags()
    else:
        if request.args.get('app_version'):
            app_version = [request.args.get('app_version')]
        else:
            app_version = None
    if not app_version and 'vacation' in user_agent:
        try:
            app_version = user_agent.split('@')[-1].split('/')[1]
        except:
            if request.args.get('version'):
                app_version = [request.args.get('version')]
            else:
                app_version = 'android_1.4.0'
    return app_version


# class Html5BaseView():
class Html5BaseMixin:
    pass


def wrap_h5(request):
    """
    Mobile device HTML5 pages
    Basically, use HTML5 and should competible with all web-views for iOS
    and Android

    user_agents.DEFAULT = 0
    user_agents.IPHONE = 1
    user_agents.IPAD = 2
    user_agents.IPOD = 3
    user_agents.ANDROID = 4
    """

    user_agent = get_user_agent(request)
    app_version = get_app_version(request)
    data = {
        'user_agent': user_agent,
        'mobile_spec': mobile_view_spec[user_agent],
    }
    data.update({'app_version': app_version})
    data.update(request.args)

    ua = request.headers.get('USER_AGENT', '').lower()

    if 'breadtrip' in ua and 'vacation' not in ua:
        data['is_breadtrip'] = True
    else:
        data['is_breadtrip'] = False
    data['is_vacation'] = True if 'vacation' in ua else False

    return data


def safe_json_load(data):
    """
        将response回来的数据解序列化
    """
    try:
        result = json.loads(data)
    except:
        return {}
    return result


class GetWechatUserData(object):
    """
    1 通过get_oauth_url 获取授权地址，redirect_url是授权后跳转会的url，如用户同意授权，返回redirect_url后会带?code码
    2 通过get_access_token，将刚刚得到的code传入，获取得到accesstoken与openid，注意，这里的accesstoken与普通的accesstoken不同
    3 通过get_user_data，将刚刚获得的access_token,openid传入，得到最终的用户信息
    """

    URL_OAUTH = 'https://open.weixin.qq.com/connect/oauth2/authorize?'
    URL_ACCESS_TOKEN = 'https://api.weixin.qq.com/sns/oauth2/access_token?'
    URL_REFRESH_TOKEN = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?'
    URL_USERINFO = 'https://api.weixin.qq.com/sns/userinfo?'

    def __init__(self, appid, secret):
        self.appid = appid
        self.secret = secret

    def get_oauth_url(self, redirect_url):
        return self.URL_OAUTH + urllib.urlencode(OrderedDict([
            ('appid', self.appid),
            ('redirect_uri', redirect_url),
            ('response_type', 'code'),
            ('scope', 'snsapi_userinfo'),
            ('state', 'STATE')
        ])) + '#wechat_redirect'

    def get_access_token(self, code=None, refresh_token=None):
        if not code and not refresh_token:
            return {}
        if code:
            response = urllib2.urlopen(
                self.URL_ACCESS_TOKEN + urllib.urlencode({'appid': self.appid,
                                                          'secret': self.secret,
                                                          'code': code,
                                                          'grant_type': 'authorization_code'}))
        elif refresh_token:
            response = urllib2.urlopen(
                self.URL_REFRESH_TOKEN + urllib.urlencode({'appid': self.appid,
                                                           'grant_type': 'refresh_token',
                                                           'refresh_token': refresh_token}))
        return safe_json_load(
            response.read())  # access_token, expires_in, refresh_token, openid, scope

    def get_user_data(self, access_token, openid, lang='zh_CN'):
        response = urllib2.urlopen(
            self.URL_USERINFO + urllib.urlencode({'access_token': access_token,
                                                  'openid': openid,
                                                  'lang': lang}))
        return safe_json_load(
            response.read())  # openid, nickname, sex, province, city,
        # country, headimgurl, privilege, unionid

#
# def wechat_code_exist(func):
#     """
#     用于微信活动来验证当前是否有code,没有则去授权的装饰器
#     被装饰的func中通过 kwargs 来获取wechat_info
#     """
#     def returned_wrapper(request, *args, **kwargs):
#         try:
#             code = request.request.args.get('code', None)
#             base = GetWechatUserData(settings.WEIXIN['public']['id'], settings.WEIXIN['public']['secret'])
#             if not code:
#                 return HttpResponseRedirect(base.get_oauth_url(settings.BASE_URL + request.request.args_full_path()))
#
#             access_res = base.get_access_token(code=code)
#             wechat_info = base.get_user_data(access_res.get('access_token'), access_res.get('openid'))
#
#             if wechat_info.get('openid', None):
#                 WechatActiveOauth.objects.get_or_create(uri=request.request.path_info, openid=wechat_info['openid'])
#
#             kwargs['wechat_info'] = wechat_info
#             return func(request, *args, **kwargs)
#         except:
#             raise Http404()
#     return returned_wrapper
